package com.ruoyi.mateproduction.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mateproduction.domain.MateProductionRecord;
import com.ruoyi.mateproduction.domain.MtCourseParameter;
import com.ruoyi.mateproduction.domain.MtCourseProject;
import com.ruoyi.mateproduction.domain.MtCourseCheck;
import com.ruoyi.mateproduction.domain.MtCourseProduct;
import com.ruoyi.mateproduction.domain.MtCourseSample;
import com.ruoyi.mateproduction.mapper.MateCourseMapper;
import com.ruoyi.mateproduction.mapper.MateDailyMapper;
import com.ruoyi.mateproduction.mapper.MtRecordMapper;
import com.ruoyi.mateproduction.service.MateCourseService;
import com.ruoyi.mtAudit.domain.MtAudit;
import com.ruoyi.mtAudit.mapper.MtAuditMapper;
import com.ruoyi.paramters.domain.Parameter;
import lombok.Data;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author
 * @Version 1.0
 */
@Service
public class MateCourseServiceImpl implements MateCourseService {

    @Autowired
    MateCourseMapper mateCourseMapper;

    @Autowired
    MtAuditMapper mtAuditMapper;

    @Autowired
    MateDailyMapper mateDailyMapper;

    @Autowired
    MtRecordMapper mtRecordMapper;

    @Override
    public int addMateCourse(MtCourseCheck mtCourseCheck) {
        int num = 0;
        Map<String, Object> resMap = new HashMap<>();
        try {
            num = mateCourseMapper.addMateCourse(mtCourseCheck);
            if (mtCourseCheck.getMtCourseProducts() != null) {
                for (MtCourseProduct mtCourseProduct : mtCourseCheck.getMtCourseProducts()) {
                    mtCourseProduct.setDeptId(SecurityUtils.getDeptId());
                    mtCourseProduct.setMtCourseId(mtCourseCheck.getMtCourseId());
                    mateCourseMapper.addMateCourseProduct(mtCourseProduct);
                }

                if (mtCourseCheck.getMtCourseProjects() != null) {
                    for (MtCourseProject mtCoureseProject : mtCourseCheck.getMtCourseProjects()) {
                        mtCoureseProject.setDeptId(SecurityUtils.getDeptId());
                        mtCoureseProject.setMtCourseId(mtCourseCheck.getMtCourseId());
                        mateCourseMapper.addMateCourseProject(mtCoureseProject);
                    }
                }

                MtAudit mtAudit = new MtAudit();
                mtAudit.setCompanyId(SecurityUtils.getDeptId());
                mtAudit.setOrderId(mtCourseCheck.getMtCourseId());
                mtAudit.setZjName(mtCourseCheck.getZjName());
                mtAudit.setOrderType("10");
                mtAudit.setOrderNum(mtCourseCheck.getCourseOrderNum());
                mtAudit.setAuditStatus("0");
                mtAudit.setAuditBy(SecurityUtils.getLoginUser().getNickName());
                mtAuditMapper.insertMtAudit(mtAudit);

                MateProductionRecord mateProductionRecord = new MateProductionRecord();
                mateProductionRecord.setIsCreateCheck("1");
                mateProductionRecord.setMtRecordId(mtCourseCheck.getMtRecordId());
                mtRecordMapper.editRecord(mateProductionRecord);
            }

        } catch (Exception e) {
            num = 0;
            mateCourseMapper.removeMateCourse(mtCourseCheck.getMtCourseId());
            mateCourseMapper.removeMateCourseProduct(mtCourseCheck.getMtCourseId());
            mateCourseMapper.removeMateCourseProject(mtCourseCheck.getMtCourseId());
            resMap.put("orderId", mtCourseCheck.getMtCourseId());
            resMap.put("orderType", "10");
            mtAuditMapper.deleteMtAuditById(resMap);

            MateProductionRecord mateProductionRecord = new MateProductionRecord();
            mateProductionRecord.setIsCreateCheck("0");
            mateProductionRecord.setMtRecordId(mtCourseCheck.getMtRecordId());
            mtRecordMapper.editRecord(mateProductionRecord);
        }
        return num;
    }

    @Override
    public List<MtCourseCheck> mateCourseList(MtCourseCheck mtCourseCheck) {
        return mateCourseMapper.mateCourseList(mtCourseCheck);
    }

    @Override
    public MtCourseCheck selectMateCourse(Long mtCourseId) {
        return mateCourseMapper.selectMateCourse(mtCourseId);
    }

    @Override
    public void remove(Long mtCourseId) {
        MtCourseCheck mtCourseCheck = mateCourseMapper.selectMateCourse(mtCourseId);
        MateProductionRecord mateProductionRecord = new MateProductionRecord();
        mateProductionRecord.setIsCreateCheck("0");
        mateProductionRecord.setMtRecordId(mtCourseCheck.getMtRecordId());
        mtRecordMapper.editRecord(mateProductionRecord);
        mateCourseMapper.removeMateCourse(mtCourseId);
        mateCourseMapper.removeMateCourseProduct(mtCourseId);
        mateCourseMapper.removeMateCourseProject(mtCourseId);
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("orderId", mtCourseId);
        resMap.put("orderType", "10");
        mtAuditMapper.deleteMtAuditById(resMap);

    }

    @Override
    public int updateCourse(MtCourseCheck mtCourseCheck) {
        int num = 0;
        if (mtCourseCheck.getMtCourseProducts() != null) {
            mateCourseMapper.removeMateCourseProduct(mtCourseCheck.getMtCourseId());
            mateCourseMapper.removeMateCourseProject(mtCourseCheck.getMtCourseId());
            for (MtCourseProduct mtCourseProduct : mtCourseCheck.getMtCourseProducts()) {
                mtCourseProduct.setDeptId(SecurityUtils.getDeptId());
                mtCourseProduct.setMtCourseId(mtCourseCheck.getMtCourseId());
                mateCourseMapper.addMateCourseProduct(mtCourseProduct);
            }

            if (mtCourseCheck.getMtCourseProjects() != null) {
                for (MtCourseProject mtCourseProject : mtCourseCheck.getMtCourseProjects()) {
                    mtCourseProject.setDeptId(SecurityUtils.getDeptId());
                    mtCourseProject.setMtCourseId(mtCourseCheck.getMtCourseId());
                    mateCourseMapper.addMateCourseProject(mtCourseProject);
                }
            }

        }
        num = mateCourseMapper.updateCourse(mtCourseCheck);
        return num;
    }

    @Override
    public List<MtCourseCheck> auditCourse(Long deptId) {
        return mateCourseMapper.auditCourse(deptId);
    }

    @Override
    public String createWord(Long mtCourseId) {
        int num = 0;
        try {
            XWPFDocument document = new XWPFDocument();
            List<MtCourseSample> list = mateCourseMapper.selectMtCourseSample(mtCourseId);
            List<MtCourseProject> parameters = mateCourseMapper.selectMtCourseProject(mtCourseId);

            XWPFParagraph paragraph = document.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun run = paragraph.createRun();
            run.setText("附件：过程检验结果");
            run.setFontSize(16);
            run.setBold(true);
            run.addBreak();

            // 创建一个表格
            XWPFTable table = document.createTable(list.size() + 2, parameters.size() + 2); // 调整行数加1
            CTTblPr tblPr = table.getCTTbl().addNewTblPr();

            tblPr.addNewTblW().setW(BigInteger.valueOf(10000)); // 设置表格宽度
            for (int i = 0; i < list.size() + 2; i++) { // 调整循环次数
                XWPFTableRow row = table.getRow(i);
                row.setHeight(800); // 设置行高
                for (int j = 0; j < parameters.size() + 2; j++) {
                    XWPFTableCell cell = row.getCell(j);
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 垂直居中对齐
                    cell.setWidth("6000"); // 设置列宽
                }
            }

            XWPFTableCell cellHeader = table.getRow(0).getCell(0);
            cellHeader.setText("样本");
            cellHeader.getParagraphArray(0).setAlignment(ParagraphAlignment.CENTER);
            cellHeader.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);

            XWPFTableCell cellSecondRow = table.getRow(1).getCell(0);
            cellSecondRow.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);

            // 填充第一列除第一行
            for (int i = 2; i < list.size() + 2; i++) {
                XWPFTableCell cell = table.getRow(i).getCell(0);
                cell.setText(list.get(i - 2).getSampleName());

                CTP ctp = cell.getCTTc().getPList().get(0);
                CTPPr ctpPr = ctp.getPPr();
                if (ctpPr == null) {
                    ctpPr = ctp.addNewPPr();
                }
                CTJc jc = ctpPr.getJc();
                if (jc == null) {
                    jc = ctpPr.addNewJc();
                }
                jc.setVal(STJc.CENTER);
            }

            // 填充第一行除第一列的数据
            for (int j = 1; j < parameters.size() + 1; j++) {
                XWPFTableCell cell = table.getRow(0).getCell(j);
                cell.setText(parameters.get(j - 1).getProcessName());

                CTP ctp = cell.getCTTc().getPList().get(0);
                CTPPr ctpPr = ctp.getPPr();
                if (ctpPr == null) {
                    ctpPr = ctp.addNewPPr();
                }
                CTJc jc = ctpPr.getJc();
                if (jc == null) {
                    jc = ctpPr.addNewJc();
                }
                jc.setVal(STJc.CENTER);

            }

            for (int j = 1; j < parameters.size() + 1; j++) {
                XWPFTableCell cell = table.getRow(1).getCell(j);
                cell.setText(parameters.get(j - 1).getCheckProject());

                CTP ctp = cell.getCTTc().getPList().get(0);
                CTPPr ctpPr = ctp.getPPr();
                if (ctpPr == null) {
                    ctpPr = ctp.addNewPPr();
                }
                CTJc jc = ctpPr.getJc();
                if (jc == null) {
                    jc = ctpPr.addNewJc();
                }
                jc.setVal(STJc.CENTER);
            }

            // 填充除第一行第一列外的数据
            for (int i = 2; i < list.size() + 2; i++) { // 修改起始行数
                for (int j = 1; j < parameters.size() + 1; j++) {
                    XWPFTableCell cellData = table.getRow(i).getCell(j);
                    cellData.setText(parameters.get(j - 1).getCheckResult());

                    CTP ctp = cellData.getCTTc().getPList().get(0);
                    CTPPr ctpPr = ctp.getPPr();
                    if (ctpPr == null) {
                        ctpPr = ctp.addNewPPr();
                    }
                    CTJc jc = ctpPr.getJc();
                    if (jc == null) {
                        jc = ctpPr.addNewJc();
                    }
                    jc.setVal(STJc.CENTER);

                }
            }


            for (int i = 0; i < list.size() + 2; i++) { // 修改循环次数
                XWPFTableCell cellDecide = table.getRow(i).getCell(parameters.size() + 1);
                if (i == 0) {
                    cellDecide.setText("判定");
                    cellDecide.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                    XWPFTableCell cellDecide1 = table.getRow(1).getCell(parameters.size() + 1);
                    cellDecide1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                    cellDecide.getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER); // 判定表头居中对齐

                } else {
                    cellDecide.setText(parameters.get(i - 1 < parameters.size() ? i - 1 : parameters.size() - 1).getResultDecide());
                    cellDecide.getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER); // 内容居中对齐
                }
            }

            // 保存文档
            String filePath = "D:\\ruoyi\\uploadPath\\download\\productionWord\\生产过程检验结果记录" + ".docx";
            FileOutputStream out = new FileOutputStream(filePath);
            document.write(out);
            out.close();
            System.out.println("Word 表格创建成功！");
        } catch (Exception e) {
            e.printStackTrace();
            num = 1;
        }
        if (num == 1) {
            return "生成失败";
        } else {
            return "/productionWord/生产过程检验结果记录.docx";
        }

    }


}

